<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>即时通讯断开重连</title>
</head>

<body>
    <script>
        /*
        * websocket 断开重连
        *
        */
        var ws;
        var lockReconnect = false;//避免重复连接
        var wsUrl = "wss://online02.tiaze.com:8282";
        var xhr = '';

        function createWebSocket(url) {
            try {
                if ('WebSocket' in window) {
                    ws = new WebSocket(url);
                } else if ('MozWebSocket' in window) {
                    ws = new MozWebSocket(url);
                } else {
                    // url = "http://" + 'xxxxxxx';
                    // ws = new SockJS(url);
                    console.log('不支持websocket');
                }

                initEventHandle();
            } catch (e) {
                reconnect(url);
            }
        }
        function xhrCreate(url, data) {
            if (xhr) {
                return;
            }
            console.log('请求数据')
            return false;
            xhr = new plus.net.XMLHttpRequest();
            xhr.onreadystatechange = function () {
                switch (xhr.readyState) {
                    case 0:
                        break;
                    case 1:
                        break;
                    case 2:
                        break;
                    case 3:
                        break;
                    case 4:
                        if (xhr.status == 200) {
                            //alert('请求成功');
                        } else { }
                        break;
                    default:
                        break;
                }
            }
            xhr.open("POST", url);
            xhr.setRequestHeader('Content-Type', 'application/json');
            xhr.send(data);
        }

        function initEventHandle() {
            ws.onclose = function (evnt) {
                console.log('websocket服务关闭了');
                reconnect(wsUrl);
            };
            ws.onerror = function (evnt) {
                console.log('websocket服务出错了');
                reconnect(wsUrl);
            };
            ws.onopen = function (evnt) {
                //心跳检测重置
                heartCheck.reset().start();
            };
            ws.onmessage = function (evnt) {
                //如果获取到消息，心跳检测重置
                //拿到任何消息都说明当前连接是正常的
                console.log('websocket服务获得数据了');

                //接受消息后的UI变化
                doWithMsg(evnt);
                heartCheck.reset().start();
            }

            //收到消息推送
            function doWithMsg(e) {
                console.log(e);
                // json数据转换成js对象
                var data = eval("(" + e.data + ")");
                var type = data.type || '';
                switch (type) {
                    // Events.php中返回的init类型的消息，将client_id发给后台进行uid绑定
                    case 'ping':
                        // 利用jquery发起ajax请求，将client_id发给后端进行uid绑定
                        break;
                    case 'login':
                        var ss = {
                            type: 'login',
                            login_type: '2',
                            client_id: data.client_id,
                            user_phone: localStorage.getItem("USERID")
                        };
                        xhrCreate('https://online02.tiaze.com/WorkPost', ss);
                        console.log(JSON.stringify(data));
                    //$.post('https://pay.tiaze.com/WorkPost', , 'json');
                    // 当mvc框架调用GatewayClient发消息时直接alert出来
                    default:
                        var data = JSON.parse(e.data);
                        if (data.msg) {
                            //语音提醒
                            console.log(JSON.stringify(data));
                            payAudio("../audio/4182.mp3");
                            var msg = JSON.parse(data.msg);
                            plus.nativeUI.confirm(data.msg.title + "\n" + data.msg.orderid + " " + data.msg.amount + "元", function (ev) {
                                if (ev.index === 1) { //点击打印
                                    if (data.msg.print_body) {
                                        var str = data.msg.print_body;
                                        var reg = /\\n/g;
                                        str = str.replace(reg, '\n');
                                        //												printTicket(data.msg.print_array);
                                        ticket(data.msg.store_name, str, data.msg.orderid);
                                        return false;
                                    }
                                    alert("系统繁忙，请稍后再试");
                                    return false;
                                } else {
                                    orderType(data.msg.type, data.msg.orderid)
                                }
                            }, "您有新订单提醒", ["详情(关闭22)", "打印"]);
                        }
                }
            };
        }


        function reconnect(url) {
            if (lockReconnect) return;
            lockReconnect = true;
            //没连接上会一直重连，设置延迟避免请求过多
            setTimeout(function () {
                createWebSocket(url);
                console.log('一直连接')
                lockReconnect = false;
            }, 2000);
        }

        //心跳检测
        var heartCheck = {
            timeout: 5000,//5秒
            timeoutObj: null,
            serverTimeoutObj: null,
            reset: function () {
                clearTimeout(this.timeoutObj);
                clearTimeout(this.serverTimeoutObj);
                return this;
            },
            start: function () {
                var self = this;
                this.timeoutObj = setTimeout(function () {
                    //这里发送一个心跳，后端收到后，返回一个心跳消息，
                    //onmessage拿到返回的心跳就说明连接正常
                    ws.send("HeartBeat");
                    self.serverTimeoutObj = setTimeout(function () {//如果超过一定时间还没重置，说明后端主动断开了
                        // ws.close();//如果onclose会执行reconnect，我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次
                    }, self.timeout)
                }, this.timeout)
            }
        }

        //初始化websocket
        createWebSocket(wsUrl);

    </script>
</body>

</html>